package org.snail.proxy.server.netty.ws;

import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import org.snail.proxy.server.config.NettyConfig;
import org.snail.proxy.server.netty.NettyServer;
import org.snail.proxy.server.netty.ProxyClientHandler;
import org.snail.proxy.server.netty.serialization.BytesDecoder;
import org.snail.proxy.server.netty.serialization.BytesEncoder;

public class WebsocketProxyServer extends NettyServer {
    private final String path;

    private Channel proxyClientChannel;
    private ProxyClientHandler proxyClientHandler;

    public WebsocketProxyServer(NettyConfig nettyConfig, String path, Channel proxyClientChannel, ProxyClientHandler proxyClientHandler) {
        super(nettyConfig);
        this.path = path;
        this.proxyClientChannel = proxyClientChannel;
        this.proxyClientHandler = proxyClientHandler;
    }

    @Override
    protected void initChannel(SocketChannel sh) {
        sh.pipeline()
                .addLast(new HttpServerCodec()) // HTTP 协议解析，用于握手阶段
                .addLast(new HttpObjectAggregator(65536)) // HTTP 协议解析，用于握手阶段
                .addLast(new WebSocketServerCompressionHandler()) // WebSocket 数据压缩扩展
                .addLast(new WebSocketServerProtocolHandler(path, null, true))
                .addLast(new BytesDecoder())
                .addLast(new BytesEncoder())
                .addLast(new WebsocketProxyHandler(proxyClientChannel, proxyClientHandler));
    }

    @Override
    public void close() {
        super.close();
        proxyClientChannel = null;
        proxyClientHandler = null;
    }

    @Override
    public void onSendMessage(String id) {

    }
}
